package org.example.journal_items.controller;

import org.example.journal_items.Entity.Todo;
import org.example.journal_items.service.TodoService;
import org.example.journal_items.common.Result;
import org.example.journal_items.security.CustomUserDetails;
import org.example.journal_items.Entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/todos")
public class TodoController {

  @Autowired
  private TodoService todoService;

  // 获取当前用户的所有待办事项
  @GetMapping
  public Result<List<Todo>> getTodos(@AuthenticationPrincipal CustomUserDetails userDetails) {
    User user = userDetails.getUser();
    List<Todo> todos = todoService.getTodosByUserId(user.getId());
    return Result.success(todos);
  }

  // 获取指定日期的待办事项
  @GetMapping("/date/{date}")
  public Result<List<Todo>> getTodosByDate(@AuthenticationPrincipal CustomUserDetails userDetails,
      @PathVariable String date) {
    User user = userDetails.getUser();
    List<Todo> todos = todoService.getTodosByUserIdAndDueDate(user.getId(), date);
    return Result.success(todos);
  }

  // 创建待办事项
  @PostMapping
  public Result<Todo> createTodo(@AuthenticationPrincipal CustomUserDetails userDetails, @RequestBody Todo todo) {
    User user = userDetails.getUser();
    todo.setUserId(user.getId());

    // 确保日期格式正确，避免时区问题
    if (todo.getDueDate() != null) {
      // 直接使用字符串日期，不进行时区转换
      String dateStr = todo.getDueDate().toString();
      todo.setDueDate(dateStr);
    }

    return todoService.createTodo(todo);
  }

  // 更新待办事项
  @PutMapping("/{id}")
  public Result<Todo> updateTodo(@PathVariable Long id, @RequestBody Todo todo) {
    todo.setId(id);
    return todoService.updateTodo(todo);
  }

  // 删除待办事项
  @DeleteMapping("/{id}")
  public Result<Void> deleteTodo(@PathVariable Long id) {
    return todoService.deleteTodo(id);
  }

  // 切换待办事项完成状态
  @PutMapping("/{id}/toggle")
  public Result<Todo> toggleTodoStatus(@PathVariable Long id, @RequestBody Todo todo) {
    return todoService.toggleTodoStatus(id, todo.getIsCompleted());
  }
}